<template>
  <div class="content">
    <nut-navbar class="navbar" z-index="5" :clickable="false" fixed safe-area-inset-top>
      <template #content>
        <span>{{ t(String(route.meta.title)) }}</span>
      </template>
      <template #left>
        <img src="/imgs/club/arrow_left.png" alt="" @click="router.go(-1)" class="arrow_left" />
      </template>
      <template #right>
        <span @click="onSubmitCreate" class="save">{{ t('save') }}</span>
      </template>
    </nut-navbar>
    <div class="create_con" :style="contentStyle()">
      <div class="top_upload">
        <nut-uploader v-if="createParams.club_logo == ''" accept=".jpg,.jpeg,.png,.gif,.webp"
          :before-xhr-upload="beforeUpload" @delete="(e) => { removeImg(e) }">
        </nut-uploader>
        <div class="club_logo_box" v-else>
          <ImgT
            :key="createParams.club_logo == 'club_logo' ? `/imgs/club/club_logo.png` : joinURL(settings.media_url, createParams.club_logo)"
            :src="createParams.club_logo == 'club_logo' ? `/imgs/club/club_logo.png` : joinURL(settings.media_url, createParams.club_logo)"
            class="club_icon" alt="club_icon" />
          <!-- <iconpark-icon class="item_icon" name="gou-f4melk0d"></iconpark-icon> -->
          <iconpark-icon name="exit" style="
            position: absolute;
            right: -6px;
            top: -2px;
            border: 1px solid #fff;
            border-radius: 50%;
            padding: 1px;
          " @click="deleteImg"></iconpark-icon>
        </div>
        <p>{{ t('club_page_updata_img') }}</p>
        <p>{{ t('club_page_gs') }}</p>
      </div>
      <div class="form_box">
        <nut-form label-position="top" ref="formRef" :model-value="createParams" :rules="rules">
          <nut-form-item prop="club_name" :rules="rules.club_name">
            <nut-input v-model.trim="createParams.club_name" show-word-limit :max-length="40"
              :placeholder="t('club_page_qsrmz')" clearable />
          </nut-form-item>
          <nut-form-item prop="club_intro" :rules="rules.club_introduction">
            <nut-textarea :rows="3" v-model.trim="createParams.club_intro" limit-show :max-length="200"
              :placeholder="t('club_page_qsrjj')" clearable />
          </nut-form-item>
        </nut-form>
      </div>

      <div class="list_box">
        <div class="other_list_item mb-10" v-for="item in buttons" :key="item.id" @click="goToPage(item)">
          <div class="item_left">
            <ImgT :src="item.icon" :key="item.icon" alt="" />
            <span>{{ t(item.text) }}</span>
          </div>
          <div class="item_right">
            <div v-if="item.value == 'check'" @click="memberAudit">
              <nut-switch :model-value="isCheckSwitch" active-color="#1DBA8B" inactive-color="#504F6F"></nut-switch>
            </div>
            <div v-else-if="item.value == 'manager'" @click="adminCreateTable">
              <nut-switch v-model="isManagerSwitch" active-color="#1DBA8B" inactive-color="#504F6F"></nut-switch>
            </div>
            <ImgT src="/imgs/club/arrow.png" alt="" v-else />
          </div>
        </div>
      </div>
    </div>

    <!-- 解散 -->
    <Modal v-model:visible="isShowWin" :title="t(club_title)" @close="">
      <div class="popup_body">
        <div class="info">{{ modalText }}</div>
        <div class="submit_btn">
          <span class="submit_close" @click="close">{{ t('cancel') }}</span>
          <Btn height="44px" width="147px" class="submit" @click="handleConfirm">{{ t('confirm') }}</Btn>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { ref, onMounted, onUnmounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showToast, showNotify } from "@nutui/nutui";
import { storeToRefs } from "pinia";
import { User } from "@/store/user";
import pinia from "@/store";
import { joinURL } from '@/utils/publicMethods'

import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";

import { Page } from "@/store/page.ts";
const PageStore = Page(pinia);
const { settings } = storeToRefs(PageStore);

const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const UserStore = User(pinia);
const { roleInfo } = storeToRefs(UserStore);
const { appHeight } = storeToRefs(User(pinia));
const formRef = ref()

// 创建俱乐部表单提交
const createParams = ref({
  club_name: '',
  club_intro: '',
  club_logo: ''
});

// 校验规则
const rules = ref({
  club_logo: [{ required: true, message: t('club_page_qscjlbtp') }],
  club_name: [
    { required: true, message: t('club_page_jlbmzbnwk') },
    { min: 2, max: 40, message: t('club_page_jlbmz40') },
  ],
  club_introduction: [
    { required: true, message: t('club_page_jlbjjbnwk') },
    { max: 200, message: t('club_page_jlbjj200') },
  ],
});

const isCheckSwitch = ref(true);
const isManagerSwitch = ref(false);

const buttons: any = ref([
  {
    id: 1,
    text: t('club_page_jlbmsh'),
    value: 'check',
    icon: '/imgs/club/check.png',
    route: '/club/create',
  },
  {
    id: 2,
    text: t('club_page_glycjpj'),
    value: 'manager',
    icon: '/imgs/club/manager.png',
    route: '',
  },
  {
    id: 3,
    text: t('club_page_cygl'),
    value: '',
    icon: '/imgs/club/member.png',
    route: '/club/member',
  },
  {
    id: 4,
    text: t('club_page_pjgl'),
    value: '',
    icon: '/imgs/club/gambling.png',
    route: '/club/handList',
  },
  {
    id: 5,
    text: t('club_page_jsjlb'),
    value: '',
    icon: '/imgs/club/disband.png',
    route: '',
  },
]);

const isShowWin = ref(false);
const club_title = ref(t('tip'));
const modalStep = ref(1);  // 用于区分弹窗的阶段
const modalText = ref('')
const clubId = ref<any>(0)

const contentStyle = () => {
  return window.matchMedia("(display-mode: standalone)").matches ||
    window.navigator.standalone
    ? { height: `calc(${appHeight.value}px - 100px)` }
    : { height: `calc(${appHeight.value}px - 100px)` };
};

// 上传图片
const beforeUpload = (xhr: any, data: any) => {
  console.log('xhr', xhr);
  console.log('data', data);
  const file = data.sourceFile;

  if (file && file.size > 1024 * 1024 * 10) {
    // 2MB限制
    showNotify.danger(t('home_page_avatar_tip'));
    return;
  }
  const formData = new FormData();
  formData.append("image", file);
  formData.append("device_id", `${roleInfo.value.id}`);
  fetch(joinURL(settings.value.api_url, `/api/upload/img`), {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((response) => {
      if (response.status == 200 || response.status == "success") {
        const urlImg = response.data.path;
        showNotify.success(t("operation_success"));
        createParams.value.club_logo = urlImg;
      } else {
        showNotify.danger(t('club_page_updata_err'));
      }
    });
};

const removeImg = (e: any) => {
  console.log('删除---', e)
}
const deleteImg = () => {
  createParams.value.club_logo = '';
}

// 获取俱乐部信息
const getClubInfo = () => {
  const req = NetPacket.req_get_club_info();
  req.club_id = clubId.value
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_get_club_info",
    callback: getClubInfoHandle,
  });
};
// 俱乐部信息返回
const getClubInfoHandle = (res: any) => {
  console.log('俱乐部信息', res)
  createParams.value.club_name = res.club_name
  createParams.value.club_intro = res.club_introduction
  createParams.value.club_logo = res.club_logo
  isCheckSwitch.value = res.is_audit === 1 ? true : false
  isManagerSwitch.value = res.is_create_table === 1 ? true : false
};

// 开关变化时的处理
// const handleSwitchChange = () => {
//   isCheckSwitch.value = !isCheckSwitch.value
//   memberAudit(); // 切换开关时调用逻辑
// };

// 免审批
const memberAudit = () => {
  console.log('审核', !isCheckSwitch.value)
  isCheckSwitch.value = !isCheckSwitch.value
  const req = NetPacket.req_club_member_audit_required();
  req.club_id = clubId.value
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_club_member_audit_required",
    callback: memberAuditHandle,
  });

}
// 免审批返回
const memberAuditHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_szcg'),
    1: t('club_page_szsb'),
  };
  if (res.result === 0) {
    showToast.text(tipStr[res.result])
  } else {
    showToast.text(tipStr[res.result])
  }
};
// 管理员创建牌局
const adminCreateTable = () => {
  console.log('前', isManagerSwitch.value)
  // isManagerSwitch.value = !isManagerSwitch.value
  console.log('后', isManagerSwitch.value)
  const req = NetPacket.req_admin_create_table();
  req.club_id = clubId.value
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_admin_create_table",
    callback: adminCreateTableHandle,
  });
}
// 管理员创建牌局返回
const adminCreateTableHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_szcg'),
    1: t('club_page_fcjzjlb'),
  };
  if (res.result === 0) {
    showToast.text(tipStr[res.result])
  } else {
    showToast.text(tipStr[res.result])
  }
};


// 保存俱乐部提交
const onSubmitCreate = () => {
  if (!createParams.value.club_logo) {
    // return showToast.text(t('club_page_qscjlbtp'))
    createParams.value.club_logo = 'club_logo'
  }
  formRef.value?.validate().then(({ valid, errors }: any) => {
    if (valid) {
      const req = NetPacket.req_modify_club_info();
      req.club_id = clubId.value
      req.club_name = createParams.value.club_name
      req.club_intro = createParams.value.club_intro
      req.club_logo = createParams.value.club_logo

      PKwebsocket.instance.send(req, true, {
        callbackName: "msg_notify_modify_club_info",
        callback: createClubHandle,
      });
    } else {
      console.warn('error:', errors);
    }
  });
};

// 修改建俱乐部返回
const createClubHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_xgcg'),
    1: t('club_page_tips1'),
    2: t('club_page_fjlbcjzgly')
  };
  if (res.result === 0) {
    showToast.text(tipStr[res.result])
    router.push('/');
  } else {
    showToast.text(tipStr[res.result])
  }
};

//解散俱乐部 
const disbandClub = () => {
  const req = NetPacket.req_disband_club();
  req.club_id = clubId.value
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_disband_club",
    callback: disbandClubHandle,
  });
}
//解散俱乐部返回
const disbandClubHandle = (res: any) => {
  const tipStr: any = {
    0: t('club_page_jscg'),
    1: t('club_page_jlbnywj'),
    3: t('club_page_fcjzjlb'),
  };
  if (res.result === 0) {
    showToast.text(tipStr[res.result])
    isShowWin.value = false
  } else {
    showToast.text(tipStr[res.result])
  }
};


const goToPage = (item: any) => {
  if (item.id === 5) {
    modalStep.value = 1;
    modalText.value = t('club_page_sfjsjlb');
    isShowWin.value = true;
    return;
  }

  if (!item.route) return;
  // const routePath = ''
  if (item.id === 3) {
    router.push({
      path: "/club/member",
      query: { club_id: clubId.value }
    })
  } else if (item.id === 4) {
    router.push({
      path: "/club/handList",
      query: { clubId: clubId.value }
    })
  }
  // const routePath = item.id === 3 
  //   ? { path: "/club/member", query: { club_id: clubId.value } } 
  //   : item.route;

  // router.push(routePath);
};

const handleConfirm = () => {
  if (modalStep.value === 1) {
    modalStep.value = 2;
    modalText.value = t('club_page_mypjhwj');
  } else {
    submitAc();
  }
};

const close = () => {
  isShowWin.value = false
}

const submitAc = () => {
  disbandClub()
  router.push('/club/myClub');
}

// watch(
//   () => route.query.club_id,
//   (newId) => {
//     clubId.value = Number(newId)
//   },
//   { immediate: true }
// );
watch(() => createParams.value.club_name, (newVal) => {
  if (newVal.length > 40) {
    createParams.value.club_name = newVal.slice(0, 40);
  }
});

watch(() => createParams.value.club_intro, (newVal) => {
  if (newVal.length > 200) {
    createParams.value.club_intro = newVal.slice(0, 200);
  }
});

watch(
  () => route.query,
  (newQuery) => {
    if (!newQuery.club_id && clubId.value) {
      // 如果路由中丢失 club_id，则重新添加
      router.replace({
        path: route.path,
        query: { ...route.query, club_id: clubId.value },
      });
    }
  },
  { immediate: true }
);

onMounted(async () => {
  const { club_id } = route.query;
  clubId.value = Number(club_id)
  await getClubInfo()
});

onUnmounted(() => {

});

</script>

<style scoped lang="scss">
.content {
  font-size: 14px;
  margin: 0 0 10px;

  .create_con {
    overflow: auto;
  }

  .top_upload {
    padding: 15% 0 0;
    position: relative;

    p {
      font-size: 15px;
      color: rgba(192, 194, 219, 1);
      text-align: center;
      margin-top: 10px;
    }

    :deep(.nut-uploader) {
      margin: 0 auto;
      width: 120px;
      height: 120px;
      background: rgba(26, 12, 66, 1);
      border: 1px solid rgba(50, 44, 89, 1);
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;

      .nut-uploader__upload {
        background: url(/imgs/club/add_ren.png) center no-repeat;
        background-size: 70px;
        border-radius: 50%;

        &::before {
          content: '';
          position: absolute;
          width: 32px;
          height: 32px;
          border-radius: 50%;
          bottom: 0;
          right: 6px;
          background: radial-gradient(100% 103.23% at 50% 0%, #1170FF 0%, #1154FF 61.51%, #6B11FF 98.5%);
        }

        svg {
          width: 24px;
          height: 24px;
          color: #fff !important;
          position: absolute;
          bottom: 4px;
          right: 10px;
        }
      }

      .nut-uploader__upload,
      .nut-uploader__preview,
      .nut-uploader__preview-img {
        width: 100%;
        height: 100%;
        margin-right: 0;

        .close {
          color: #fff;
        }
      }

      .nut-uploader__preview__progress {
        display: none;
      }
    }

  }

  .club_logo_box {
    width: 120px;
    height: 120px;
    margin: 0 auto;
    position: relative;

    .item_icon {
      background-color: #fff;
      border-radius: 50%;
      font-size: 16px;
      position: absolute;
      bottom: -6px;
      left: calc(50% - 6px);
      // transform: translateX(-50%);
    }

    img {
      width: 120px;
      height: 120px;
      border-radius: 50%;
    }
  }

  .form_box {
    width: 347px;
    height: 176px;
    margin: 10px auto 0;
    padding: 10px;
    border-radius: 8px;
    background: #100E26;
    box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;

    form {
      .add_title {
        font-size: 14px;
        color: #fff;
        margin-bottom: 10px;
      }

      :deep(.nut-cell-group__wrap) {
        box-shadow: none;
        background: none;
        margin: 0;

        .nut-cell {
          background: none;
          padding: 0;
          margin-bottom: 14px;

          &::after {
            border: none;
          }

          &.nut-form-item {

            .nut-form-item__label {
              color: #fff;
            }

            .nut-input,
            .nut-textarea {
              color: #fff;
              width: 100%;
              background: #1D1C3C;
              border: 1px solid #1D1C3C;
              border-radius: 8px;
              padding: 10px !important;

              .nut-textarea__textarea {
                color: #fff;
              }
            }

          }
        }
      }

    }
  }

  .arrow_left {
    width: 24px;
    height: 24px;
  }

  :deep(.nut-navbar__right) {
    padding: 0;
  }

  .save {
    width: 56px;
    height: 32px;
    line-height: 32px;
    text-align: center;
    color: #FFFFFF;
    background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
    box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
    border-radius: 8px;
  }

  .list_box {
    width: 347px;
    margin: 0 auto;

    .other_list_item {
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      // padding: 0 14px;

      .item_left {
        display: flex;
        align-items: center;

        img {
          width: 20px;
          height: 20px;
          margin-right: 8px;
        }

        span {
          color: #FFFFFF;
          font-weight: 500;
          font-size: 13px;
        }
      }

      .item_right {
        img {
          width: 14px;
          height: 14px;
        }
      }

      .arrow {
        height: 16px
      }
    }
  }

}

.popup_body {
  color: #fff;
  padding: 10px;

  .info {
    margin-bottom: 10px;
    text-align: center;
    color: #FFFFFF;
    margin: 24px 0;
  }

  .submit_btn {
    margin: 20px 0;
    display: flex;
    justify-content: space-evenly;

    .submit_close {
      width: 147px;
      height: 42px;
      color: #FFFFFF;
      text-align: center;
      line-height: 44px;
      background: #282747;
      box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
      border-radius: 8px;
    }
  }
}
</style>
